package org.easyspec.domain

import org.easyspec.application.*
import java.text.*
import groovy.xml.*

class HtmlReportGenerator {
	FileOutputHandler fileSystem = new LocalDiskOutput()
	String path
	String outputFileName = 'index.html'
	def clock = new LiveClock()

	String generateReport(Specifications specifications) {
		return generateReport(specifications, 'EasySpec Report')
	}

	String generateReport(Specifications specifications, String title) {
		def outputFile
		if (path != null) {
			outputFile = "$path/$outputFileName"
		}
		else {
			outputFile = outputFileName
		}
		fileSystem.writeToFile(outputFile, generate(specifications, title))
		return 'index.html'
	}

	def generate(specifications, titleText) {
		def writer = new StringWriter()
		def page = new MarkupBuilder(writer)
		def format = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss")

		page.html {
			head {
				title "EasySpec Report"
				link(href:"http://easyspec.googlecode.com/svn/trunk/resources/css/styles.css", media:"all", rel:"Stylesheet", type:"text/css")
			}
			body {
				div(class:'reportTitle') {
					span titleText
				}
				div(class:'reportTime') {
					span format.format((Date)clock.currentTime())
				}
				specifications.each { spec ->
					def idString = spec.interest + spec.context
					idString = idString.replaceAll(' ', '')
					table(width:'100%', id:idString, class:"specTable") {
						//The Header Row has the interest and context
						tr {
							def specStyle = spec.isImplemented ? "implementedSpec" : "pendingSpec"
							td(class:specStyle) {
								span "$spec.interest, $spec.context"
							}
						}
						//One Row for each behavior
						spec.behaviors.each { behavior ->
							tr {
								def styleClass = behavior.isImplemented ? 'implemented' :  'pending'
								td(class:styleClass) {
									span behavior.detail
								}
							}
						}
					}
				}
			}
		}

		return writer.toString();
	}
}